﻿create PROCEDURE Sync.SP_Governorates_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @Governorates_Temp TABLE 
		(
			GovernorateID UniqueIdentifier,
			[GovernorateName] nvarchar(50),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @Governorates_Temp 
	   SELECT	Tbl.Col.value('GovernorateID[1]','uniqueidentifier') GovernorateID,
                Tbl.Col.value('GovernorateName[1]', 'nvarchar(50)') [GovernorateName],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/Governorates') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[Governorates] ([GovernorateID],[GovernorateName])
	SELECT t.[GovernorateID],t.[GovernorateName]
	FROM  @Governorates_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.Governorates_Tracking s
        WHERE t.GovernorateID = s.GovernorateID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[Governorates]
	SET [Governorates].[GovernorateName] = t.[GovernorateName] 
	FROM [dbo].[Governorates] s JOIN @Governorates_Temp t 
    ON t.GovernorateID = s.GovernorateID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.Governorates_Tracking r
				  WHERE t.GovernorateID = r.GovernorateID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[Governorates]
    FROM @Governorates_Temp t JOIN [dbo].[Governorates] s
    ON t.GovernorateID = s.GovernorateID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














